package com.itheima01;

import java.sql.*;
import java.util.ResourceBundle;

/*
    JDBC工具类
 */
@SuppressWarnings("all")
public class JDBCUtils {
    //1.私有构造方法
    private JDBCUtils() {
    }

    //2.声明所需要的配置变量
    private static String driverClass;
    private static String url;
    private static String username;
    private static String password;
    private static Connection con;

    //3.提供静态代码块。读取配置文件的信息为变量赋值，注册驱动
    static {
        try {
            //读取配置文件的信息为变量赋值
            ResourceBundle rb = ResourceBundle.getBundle("config");
            driverClass = rb.getString("driverClass");
            url = rb.getString("url");
            username = rb.getString("username");
            password = rb.getString("password");
            //注册驱动
            Class.forName(driverClass);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //4.提供获取数据库连接方法
    public static Connection getConnection() {
        Connection con = null;
        try {
            con = DriverManager.getConnection(url, username, password);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return con;
    }

    //5.提供释放资源的方法
    public static void close(ResultSet res, Statement statement, Connection con) {
        if (res != null) {
            try {
                res.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (statement != null) {
            try {
                statement.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (con != null) {
            try {
                con.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

/*    public static void close(Statement statement, Connection con) {
        if (statement != null) {
            try {
                statement.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (con != null) {
            try {
                con.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }*/
}
